package service

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/robfig/cron"
	"log"
	__ "user_service/basic/proto"
	"user_service/handler/dao"
	"user_service/handler/model"
)

// 订单添加
func (s *Server) OrderCreate(_ context.Context, in *__.OrderCreateReq) (*__.OrderCreateResp, error) {
	var good model.Good
	dao.GetOneByFields(&model.Good{Id: uint(in.GoodId)}, &good)
	if good.Id == 0 {
		return nil, errors.New("当前商品不存在")
	}

	order := model.Order{
		OrderSn: uuid.NewString(),
		UserId:  uint(in.UserId),
		GoodId:  uint(in.GoodId),
		Price:   good.Price,
	}
	err := dao.Create(&order)
	if err != true {
		return nil, errors.New("订单创建失败")
	}
	UpdateOrderStatus()

	return &__.OrderCreateResp{
		Id: int64(order.Id),
	}, nil
}

func UpdateOrderStatus() {
	c := cron.New()
	spec := "* */1 * * * ?"
	err := c.AddFunc(spec, func() {
		err := dao.Update(&model.Order{Status: 2})
		if err != true {
			log.Fatal("订单状态修改失败")
		}
	})
	fmt.Println(err)
	c.Start()
	select {}
}

// 订单详情
func (s *Server) OrderDetail(_ context.Context, in *__.OrderDetailReq) (*__.OrderDetailResp, error) {

	var order model.Order
	err := dao.GetOneByFields(&model.Order{Id: uint(in.Id)}, &order)
	if err != true {
		return nil, errors.New("订单信息查询失败")
	}

	return &__.OrderDetailResp{
		Id:      int64(order.Id),
		OrderSn: order.OrderSn,
		UserId:  int64(order.UserId),
		GoodId:  int64(order.GoodId),
		Stock:   int64(order.Status),
		Price:   float32(order.Price),
	}, nil
}

// 模拟支付
func (s *Server) Pay(_ context.Context, in *__.PayReq) (*__.PayResp, error) {
	var order model.Order
	err := dao.GetOneByFields(&model.Order{Id: uint(in.Id)}, &order)
	if err != true {
		return nil, errors.New("订单信息查询失败")
	}

	return &__.PayResp{
		Id:      int64(order.Id),
		OrderSn: order.OrderSn,
		Stock:   int64(order.Status),
		Price:   float32(order.Price),
	}, nil
}
